<?php

use Biz\cache\lottery\CSpringHomeGift;
use Biz\cache\lottery\CSpringHomeLottery;

ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

$date = $argv[1] ?? date('Ymd');

$h = date("H");
$sign = 'pool';
$key = CSpringHomeLottery::lockKey($sign);
$ttl = CSpringHomeLottery::ttl($key);
$uuid = null;
try {

    if ($ttl > 0) throw new Exception('lock 1');

    $uuid = CSpringHomeLottery::lock($sign);

    if (empty($uuid)) throw new Exception('lock 2');

    if ($h < 8) {
        throw new Exception(" 停止抽奖时间");
    }
    $products = \Biz\cache\lottery\CSpringHomeGift::getGiftPool($date);

    $total = count($products);

    if ($total == 0) throw new Exception(" 奖品池为空");

    $last = mktime(20, 0, 0) - time();
    $send = 1;
    $rand_time = 100000;
    $seconds = 60;
    $expire = 'none';
    if ($last >= 0) {
        $seconds = ceil($last / $total);

        $send = min(rand(1, 2), $total); //前面出的多,后面出的少
        $rand_time = rand(0, 50000000);
        $expire = CSpringHomeLottery::expire($key, $seconds);
    }
    if ($rand_time > 0) usleep($rand_time);
    $rs = CSpringHomeGift::pushGiftToList($date, 1);
    if ($rs) {
        $uuid = null;
    }
    $push = array_slice($products, 0, $rs);
    echo date('Y-m-d H:i:s') . " lock $seconds | expire $expire| info 总共 $total | 推送 " . implode(',', $push), PHP_EOL;

} catch (Exception $e) {
    echo date('Y-m-d H:i:s') . " $key => ttl $ttl | error " . $e->getMessage(), PHP_EOL;
} finally {
    if (!empty($uuid)) CSpringHomeLottery::unlock($sign, $uuid);
}

